<?php 
class ATTACHMENTS{
	var $dbErrorMsg = "Failed set/get data from database (Class attachments): ";
	function getFile($fileId){
		$sql="select * from `".tblPrefix."attachments` where `id`=".$fileId;
		$res=MAIN::returnArray($sql);
		return $res[0];
	}
	function setFile($file, $relatedId, $relatedTable, $note, $pathPrefix=""){
		$userId=MAIN::decode($_SESSION[svar]);		
		//	File name		
		$fileName = $file['name'];
		$displayName = explode('.',$file['name']);
		$displayName = $displayName[0];
		$filesize = $file['size'];
		$path = $pathPrefix."attachments/".$fileName;
		//Check if there is file with same name on server
		while(file_exists($path)){
			$fileName = rand(100, 999).$fileName;
			$path =  $pathPrefix."attachments/".$fileName;
		}	
	    if(move_uploaded_file($file['tmp_name'], $path)){
	    	LOGS::setLog('INSERT', tblPrefix."attachments", "userId:".$userId.",relatedId:".$relatedId.",relatedTable:".$relatedTable.",filename:".$file['name'], $userId);
			$sql="insert into `".tblPrefix."attachments` (`name`,`filename`,`extension`,`size`,`related_id`,`related_table`,`note`,`user_id`,`modif`) value ('".$displayName."','".$path."','".$file['type']."','".$filesize."',".$relatedId.",'".$relatedTable."','".$note."',".$userId.",NOW())";
	    	MAIN::executeCommand($sql);
	    	return mysql_insert_id();;
	    }else{
	    	echo "fail!!!";	    
	    	return false;
	    }
	}	
	function delFile($fileId){
		$file=$this->getFile($fileId);
		$sql="delete from `".tblPrefix."attachments` where `id`=".$fileId;
		unlink($file['filename']);
		MAIN::executeCommand($sql);
	}
	function getFiles($relatedId,$relatedTable){
		$sql="select * from `".tblPrefix."attachments` where `related_id`=".$relatedId." AND `related_table`='".$relatedTable."'";
		return MAIN::returnArray($sql);
	}
}
?>